package com.hfjyz.registration.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;

import com.hfjyz.registration.command.ScoreImportCommand;
import com.hfjyz.registration.command.ScoreInputCommand;
import com.hfjyz.registration.dao.AdmissionDao;
import com.hfjyz.registration.model.Admission;

public class ScoreServiceImpl extends AbstractServiceImpl implements
		ScoreService {
	private AdmissionDao admissionDao;

    /**
     * @return the admissionDao
     */
    public AdmissionDao getAdmissionDao() {
        return admissionDao;
    }

    /**
     * @param admissionDao
     *            the admissionDao to set
     */
    public void setAdmissionDao(AdmissionDao admissionDao) {
        this.admissionDao = admissionDao;
    }

    @Override
    public void inputScore(ScoreInputCommand cmd, BindException errors) throws Exception {
        Admission admission = admissionDao.get(cmd.getIdCardNo(), cmd.getAdmissionId(), cmd.getExam().getId());
        if (admission == null) {
            errors.rejectValue("idCardNo", "idCardNo.error", "输入的身份证号与准考证号不匹配，请确认后重新输入。");
            return;
        }
        double score = Double.parseDouble(cmd.getScore());
        admission.setScore(score);
        admissionDao.update(admission);
    }

    @Override
    public void importScore(ScoreImportCommand cmd,
            MultipartFile multipartFile, BindException errors) throws Exception {

        Workbook workbook = null;
        try {
            if (multipartFile.getOriginalFilename().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(multipartFile.getInputStream());
            } else {
                workbook = new HSSFWorkbook(multipartFile.getInputStream());
            }
        } catch (FileNotFoundException e) {
            errors.reject("error.loadnousertem", "failed loadquestion!");
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获得指定的sheet
        Sheet sheet = workbook.getSheetAt(0);
        // 获得sheet总行数
        int rowCount = sheet.getLastRowNum();
        if (rowCount <= 1) {
            return;
        }

        Integer examId = cmd.getExam().getId();
        List<Admission> admissions = admissionDao.getAllByExamId(examId);
        List<Admission> updates = new ArrayList<Admission>(admissions.size());
        List<Admission> unimported = new ArrayList<Admission>(admissions.size());
        String idCardNo, admissionId;
        Double score;
        Admission admission;
        // 遍历行row
        for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++) {

            // 获得行对象
            Row row = sheet.getRow(rowIndex);
            if (null != row) {
                idCardNo = getCellString(row.getCell(0));
                admissionId = getCellString(row.getCell(1));
                String scoreStr = getCellString(row.getCell(2));

                admission = findAdmission(idCardNo, admissionId, admissions);
                if (admission != null) {
                    admission.setScore(Double.valueOf(scoreStr));
                    updates.add(admission);
                } else {
                    // TODO
                    unimported.add(new Admission(0, examId, admissionId));
                }
            }
        }
        admissionDao.updateAll(updates);
    }
    
    private String getCellString(Cell cell) {
        return new DataFormatter().formatCellValue(cell);
    }
    
    private Admission findAdmission(String idCardNo, String admissionId, List<Admission> admissions) {
        for (Admission a : admissions) {
            if (admissionId.equals(a.getCode())) {
                return a;
            }
        }
        return null;
    }

}
